import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/auth'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    meta: { title: '登录' }
  },
  {
    path: '/home',
    component: () => import('@/views/home/index'),
    meta: { title: '首页', requiresAuth: true }
  },
  {
    path: '/bank-list',
    component: () => import('@/views/bank-list/index'),
    meta: { title: '银行卡列表', requiresAuth: true }
  },

  // 错误页面
  {
    path: '/401',
    component: () => import('@/views/error-page/401'),
    hidden: true
  },
  {
    path: '/410',
    component: () => import('@/views/error-page/410'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404'),
    hidden: true
  },
  // 当没有任何其他路由规则匹配到当前的路径时，它将被匹配
  { path: '*', redirect: '/401', hidden: true }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 检查目标路由中是否有需要进行身份验证的
  if (to.meta.requiresAuth) {
    // 如果已经验证，则正常跳转
    if (getToken()) {
      next()
    }

    // 如果没有验证，重定向到登录页面
    else {
      next({ path: '/login' })
    }
  } else {
    next() // 如果不需要身份验证，直接跳转
  }
})

export default router
